package com.star.image;

import java.awt.image.*;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import lombok.Data;

public class CutImage {


    public static void main(String[] args) {
        // 读取本地图片
        BufferedImage read = null;

        TrafficDTO trafficDTO = new TrafficDTO();
        trafficDTO.setLeft(5040);
        trafficDTO.setRight(6768);
        trafficDTO.setTop(2152);
        trafficDTO.setBottom(4408);
        try {
            read = ImageIO.read(new File("/Users/star/IdeaProjects/java-basic/src/main/resources/images/SaloonCar_Big_0725d9f926744baaa612fa7ce418edb4.jpg"));
            BufferedImage bufferedImage = extractImage(trafficDTO, read);
            ImageIO.write(bufferedImage, "png", new File("/Users/star/IdeaProjects/java-basic/src/main/resources/images/cut.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage extractImage(TrafficDTO dto, BufferedImage read) {
        long left = dto.getLeft() * read.getWidth() / 8192;
        long right = dto.getRight() * read.getWidth() / 8192;
        int imgHeight = read.getHeight();
        long top = dto.getTop() * imgHeight / 8192;
        long bottom = dto.getBottom() * imgHeight / 8192;
        int width = (int) (right - left);
        int height = (int) (Math.min(bottom - top + 60, imgHeight - top));
        BufferedImage recImg;
        if (width == 0 || height == 0) {
            recImg = read;
        } else {
            recImg = read.getSubimage((int) left, (int) top, width, height);
        }
        return recImg;
    }


    @Data
    public static class TrafficDTO {
        private long left;
        private long right;
        private long top;
        private long bottom;
    }
}
